<template>
    <div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="书本名称" prop="bookName">
                <el-input v-model="ruleForm.bookName"></el-input>
            </el-form-item>
            <el-form-item label="书本类别" prop="bookTypeName">
                <el-select :data="bookTypeList" v-model="ruleForm.bookTypeName" clearable placeholder="请选择书本类别">
                   <el-option v-for="item in bookTypeList2"
                              :key="item.id"
                              :label="item.typeName"
                              :value="item.typeName">
                   </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="书本价格" prop="bookPrice">
                <el-input v-model="ruleForm.bookPrice"></el-input>
            </el-form-item>
            <el-form-item label="书本描述" prop="bookDesc">
                <div style="margin: 20px 0;"></div>
                <el-input v-model="ruleForm.bookDesc"
                type="textarea"
                          placeholder="请输入内容"
                          maxlength="100"
                          show-word-limit>
                </el-input>
            </el-form-item>
            <el-form-item label="书本封面照片">
<!--                <el-upload-->

<!--                        class="avatar-uploader"-->
<!--                        action="https://jsonplaceholder.typicode.com/posts/"-->
<!--                        :show-file-list="false"-->
<!--                        :on-success="handleAvatarSuccess"-->
<!--                        :before-upload="beforeAvatarUpload">-->
<!--                    <img v-if="bookImg" :src="bookImg" class="avatar">-->
<!--                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--                </el-upload>-->
              <el-upload ref="upfile"
                         action="#"
                         :auto-upload="false"
                         :on-change="handleChange"
                         :show-file-list="false"
                         :limit="1"
                         accept="image/png,image/gif,image/jpg,image/jpeg"
              >
                <img v-if="imgUrl" :src="imgUrl" width="180px" height="180px"/>
                <i v-else class="el-icon-plus" style="font-size: xxx-large;margin-top: 70px"></i>
              </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" style="width:30%" @click="onSubmit('ruleForm')">发布商品</el-button>
                <el-button type="success" style="width:30%" @click="letterSubmit('ruleForm')">保存预发布</el-button>
                <el-button type="danger" style="width:30%" @click="clearSubmit('ruleForm')">清空</el-button>
            </el-form-item>
        </el-form>
      <buttom/>
    </div>


</template>

<script>
    import axios from "axios";
    import Fluid from "@/components/fluid";
    import buttom from "@/components/book/buttom";

    export default {
        name: "bookput",
      components:{
        Fluid,
        buttom,
      },
        data(){
            return {
                user: this.$store.state.userinfo.user!=null?this.$store.state.userinfo.user.user.id:'',
                bookTypeList:[],
                bookTypeList2:[],
                value:'',
                text: '',
                textarea: '',
                fileList:[],
                bookImg: '',
                imgUrl:'',
                ruleForm:{
                    bookName:'',
                    bookTypeName:'',
                    bookPrice:'',
                    bookDesc:'',
                    // bookImg: '',
                },
                rules:{
                    bookName:[
                        { required: true, message: '请输入书本名称', trigger: 'blur'}
                    ],
                    bookTypeName:[
                        {required: true, message: '请输入书本类别', trigger: 'change'}
                    ],
                    bookPrice:[
                        {required: true, message: '请输入书本价格', trigger: 'blur'}
                    ],
                    bookDesc:[
                        {required: true, message: '请输入书本介绍', trigger: 'blur'}
                    ]
                }
            };
        },
        methods: {

            // handleAvatarSuccess(res, file) {
            //     this.bookImg = URL.createObjectURL(file.raw);
            //     console.log(file.raw)
            //     this.fileList=file.raw;
            // },
            // beforeAvatarUpload(file) {
            //     const isJPG = file.type === 'image/jpeg';
            //     const isLt2M = file.size / 1024 / 1024 < 2;
            //
            //     if (!isJPG) {
            //         this.$message.error('上传头像图片只能是 JPG 格式!');
            //     }
            //     if (!isLt2M) {
            //         this.$message.error('上传头像图片大小不能超过 2MB!');
            //     }
            //     return isJPG && isLt2M;
            // },
          handleChange(file,fileList) {
            const isLt2M = file.size / 1024 / 1024 < 2     //这里做文件大小限制
            if (!isLt2M) {
              this.$message({
                message: '上传文件大小不能超过 2MB!',
                type: 'warning'
              });
              this.$refs.upfile.clearFiles();
              return isLt2M
            } else {
              //多次上传
              this.$refs.upfile.clearFiles(); //上传成功之后清除历史记录

              this.fileList = fileList;
              console.log(file)
              //生成本地图片的url，直接src显示,删除或移动后url就失效了
              this.imgUrl = URL.createObjectURL(file.raw);
              console.log("11111"+file.raw)
              console.log(this.imgUrl)
            }
          },
            onSubmit(formName){
                // this.$refs[formName].validate((valid) => {
                //     if (valid) {
                //         alert('发布成功!');
                //     } else {
                //         console.log('发布失败!!');
                //         return false;
                //     }
                // });
                var formData=new FormData();
              var face = this.fileList[0];
                // for(let key in this.ruleForm){
                //     formData.append(key,this.ruleForm[key]);
                // }
                formData.append("book",JSON.stringify(this.ruleForm));
                formData.append("file",face.raw);
                formData.append("id",this.user);

                console.log("名字"+this.ruleForm.bookName);
                if(this.ruleForm.bookName.length!=0 && this.ruleForm.bookDesc.length!=0 && this.ruleForm.bookPrice.length!=0 && this.ruleForm.bookTypeName.length!=0){
                    this.axios({
                        method:"post",
                        url:"/bookput/insert",
                        headers:{
                            "Content-Type": "multipart/form-data"
                        },
                        // withCredentials:true,
                        data:formData
                    }).then((res)=>{
                        if(res.data.code == 0){
                          alert("发布成功"),
                              this.$refs[formName].resetFields();
                        }else{
                          alert("发布失败")
                        }
                    })
                }else{
                    alert("内容不能为空")
                }
            },

            letterSubmit(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        alert('保存成功!');
                    } else {
                        console.log('保存失败!!');
                        return false;
                    }
                });
                let formData=new FormData();

                // for(let key in this.ruleForm){
                //     formData.append(key,this.ruleForm[key]);
                // }
                formData.append("book",JSON.stringify(this.ruleForm));
                formData.append("file",this.fileList[0].raw);
                formData.append("id",this.user);

                console.log("名字"+this.ruleForm.bookName);
                if(this.ruleForm.bookName.length!=0 && this.ruleForm.bookDesc.length!=0 && this.ruleForm.bookPrice.length!=0 && this.ruleForm.bookTypeName.length!=0){
                    this.axios({
                        method:"post",
                        url:"/bookput/keep",
                        headers:{
                            "Content-Type": "multipart/form-data"
                        },
                        // withCredentials:true,
                        data:formData
                    }).then((res)=>{
                        console.log(res);
                    })

                }else{
                    alert("内容不能为空")
                }
            },

            clearSubmit(formName){
                this.$refs[formName].resetFields();
            }
        },
        //传入书本的类别
        created(){
            this.axios.post('/book/bookType').then(
                Response => {
                    console.log(Response)
                    this.bookTypeList=Response.data.data.bookTypeList;
                    for(let i=1;i<7;i++){
                        // console.log(i)
                        this.bookTypeList2[i-1]=this.bookTypeList[i];
                    }
                },
                error => {
                    console.log(error);
                }
            )
        },
    }
</script>

<style scoped>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>